package com.xhg.controller;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Model;

/**
 * CommonController
 */
public class BaseController<T extends Model> extends Controller {
	
	private static Logger log = Logger.getLogger(BaseController.class);
	protected static String msg = null;
	
	protected Map<String, Object> paramMap;
	protected List<Object> paramList;
	
	/**
	 * 获取request中所有参数返回Map
	 */
	public Map<String, Object> getParamMap() {
		paramMap = new HashMap<String, Object>();
		Enumeration<String> paramNames = getParaNames();
		String paramName = "";
		String paramValue = "";
		while (paramNames.hasMoreElements()) {
			paramName = paramNames.nextElement();
			paramValue = getPara(paramName);
			paramMap.put(paramName, paramValue);
		}
		return paramMap;
	}
	/**
	 * 获取前端传来的数组对象并响应成Model列表
	 */
	public List<T> getModels(Class<T> modelClass, String modelName) {
		List<String> nos = getModelsNoList(modelName);
		List<T> list = new ArrayList<T>();
		for (String no : nos) {
			T m = getModel(modelClass, modelName + "[" + no + "]");
			if (m != null) {
				list.add(m);
			}
		}
		return list;
	}
	/**
	 * 提取model对象数组的下标
	 */
	private List<String> getModelsNoList(String modelName) {
		// 提取标号
		List<String> list = new ArrayList<String>();
		String modelNameAndLeft = modelName + "[";
		Map<String, String[]> parasMap = getRequest().getParameterMap();
		for (Entry<String, String[]> e : parasMap.entrySet()) {
			String paraKey = e.getKey();
			if (paraKey.startsWith(modelNameAndLeft)) {
				String no = paraKey.substring(paraKey.indexOf("[") + 1,
						paraKey.indexOf("]"));
				if (!list.contains(no)) {
					list.add(no);
				}
			}
		}
		return list;
	}
}
